<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title>{%block title %}{%endblock%} - {{APP_NAME}}</title>
    {%if DEBUG%}
    <script src="/static/clipboard.js"></script>
    <script src="/static/jquery-3.3.1.js"></script>
    <script src="/static/vue.js"></script>
    <script src="/static/semantic.js"></script>
    <script src="/static/jquery.cookie.js"></script>
    <link rel="stylesheet" href="/static/semantic.css">
    <script src="https://cdn.bootcss.com/axios/0.19.0-beta.1/axios.js"></script>
    {%else%}
    <!-- <script src="/static/clipboard.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.4.1/dist/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/vue@2.6.11/dist/vue.min.js"></script>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/semantic-ui@2.4.2/dist/semantic.min.css">
    <script src="https://cdn.jsdelivr.net/npm/semantic-ui@2.4.2/dist/semantic.min.js"></script> -->
    <script src="//cdn.staticfile.org/jquery/3.3.1/jquery.min.js"></script>
    <script src="//cdn.staticfile.org/vue/2.5.17/vue.min.js"></script>
    <script src="//cdn.staticfile.org/semantic-ui/2.3.3/semantic.min.js"></script>
    <script src="//cdn.staticfile.org/jquery-cookie/1.4.1/jquery.cookie.min.js"></script>
    <link href="//cdn.staticfile.org/semantic-ui/2.3.3/semantic.min.css" rel="stylesheet">
    <!-- <script src="https://cdn.bootcss.com/axios/0.19.0-beta.1/axios.min.js"></script> -->
    <script src="https://cdn.staticfile.org/axios/0.19.2/axios.min.js"></script>
    {%endif%}
    <link href="https://cdn.staticfile.org/KaTeX/0.11.1/katex.min.css" rel="stylesheet">
    <script src="https://cdn.staticfile.org/KaTeX/0.11.1/katex.min.js"></script>
    <!-- <script src="https://cdn.bootcss.com/KaTeX/0.10.2/contrib/auto-render.min.js"></script> -->
    <script src="https://cdn.staticfile.org/showdown/1.9.1/showdown.min.js"></script>
    <script src="https://cdn.staticfile.org/SyntaxHighlighter/3.0.83/scripts/shCore.min.js"></script>
    <!-- <script src="https://unpkg.com/axios/dist/axios.min.js"></script> -->
    <script src="https://cdn.staticfile.org/socket.io/2.3.0/socket.io.js"></script>
    <link rel="stylesheet" href="/static/style.css">
    <script src="/static/md5.js"></script>
    {%if DEBUG%}
    <script>
        const debug_post = function (url, data) {
            $.post(url, data).done(ctx => console.log(JSON.parse(ctx)));
            // axios.post(url, data).then((ret) => {
            //     console.log(JSON.parse(ret));
            // });
        }
    </script>
    {%endif%}
    <script>
        const renderLatex = function (str) {
            return katex.renderToString(String(str), { throwOnError: false });
        };
        const getRequest = function () {
            var url = location.search; //获取url中"?"符后的字串  
            var theRequest = new Object();
            if (url.indexOf("?") != -1) {
                var str = url.substr(1);
                strs = str.split("&");
                for (var i = 0; i < strs.length; i++) {
                    theRequest[strs[i].split("=")[0]] = decodeURIComponent(strs[i].split("=")[1]);
                }
            }
            return theRequest;
        }
        const md5WithSalt = function (password) {
            return hex_md5(password + "{{SALT}}")
        };
        const copy_text = function (text) {
            const elem = document.createElement("textarea");
            $("body").append(elem);
            elem.value = text;
            elem.select();
            document.execCommand("copy");
            $(elem).remove();
            return elem;
        };
        const show_error_modal = function (text, title = "错误") {
            $("#global-error-header").text(title)
            $("#global-error-text").text(text);
            $("#global-error-model").modal("show");
        };
        const showErrorModal = show_error_modal;
        const CSRF_TOKEN="{%if USING_CSRF_TOKEN %} {{csrf_token() }} {%else%}{%endif%}";
        $.ajaxSetup({
            beforeSend: function (xhr, settings) {
                xhr.setRequestHeader("X-CSRFtoken", CSRF_TOKEN);
            }, error: function (xhr, status, err) {
                show_error_modal(xhr.responseText, xhr.status + " " + err);
                throw err;
            }
        });

        axios.interceptors.request.use((config) => {
            // config.headers['X-Requested-With'] = 'XMLHttpRequest';
            // config.headers["content-type"] = "application/x-www-form-urlencoded";
            config.headers["X-CSRFtoken"] = CSRF_TOKEN;
            return config;
        });
        axios.interceptors.response.use(resp => {
            console.log(resp);
            return resp;
        }, err => {
            let response = err.response;
            showErrorModal(response.data, response.status + " " + response.statusText)
            // console.log("qwq", Object.keys(err));
            // console.log(err.response);
            // console.log(typeof err)
        });
        const judge_status = {
            done: false, data: {}
        };
        //用于显示分数的小标签
        Vue.component("score-label", {
            delimiters: ["{[", "]}"],
            props: ["score", "full_score"],
            methods: {
                get_text_color(ratio) {
                    ratio *= 100;
                    if (ratio <= 50) return "red";
                    else if (ratio <= 70) return "orange";
                    else if (ratio < 100) return "darkorange";
                    else return "green";
                }
            }, template: "<span :style=\"'font-weight: bold;color: '+get_text_color(score/full_score)\">{[score]}/{[full_score]}</span>"
        });
        Vue.component("page-menu", {
            delimiters: ["{[", "]}"],
            props: {
                pageCount: Number, callback: Function, currentPage: Number
            }, data() {
                return { page: 1 }
            },
            mounted() {
                this.page = this.currentPage;
            },
            computed: {
                pages() {
                    const arr = new Array();
                    for (var i = 1; i <= this.pageCount; i++) arr.push(i);
                    if (arr.indexOf(this.page) > 5) {
                        arr.splice(1, arr.indexOf(this.page) - 4);
                        arr.splice(1, 1, -1);
                    }
                    if (arr.indexOf(this.page) + 5 <= arr.length) {
                        arr.splice(arr.indexOf(this.page) + 5, arr.length - 2 - (arr.indexOf(this.page) + 5) + 1);
                        arr.splice(-2, 1, -1);
                    }
                    return arr;
                }
            },
            template: `<div class="ui center aligned container">
            <div class="ui pagination menu" v-if="pages.find(x=>x!=-1)">
                <a class="item" v-for="item in pages"
                    :class="{disabled:item==-1||item==page,active:item==page}"
                    v-on:click="(item==-1)?null:(page=item,callback(item))"
                    >{[
                    item==-1?"...":item]}</a>
            </div>
        </div>`
        });
        //显示评测状态的标签
        Vue.component("judge-status", {
            delimiters: ['{[', ']}'],
            props: ["status"],
            template: "<div :class='\"ui \"+get_color(status)+\" label\"'><i :class='get_icon(status) '></i>{[get_text(status)]}</div>",
            data() {
                return {
                    judgeStatus: judge_status
                }
            },
            methods: {
                get_icon: function (x) {
                    if (!this.judgeStatus.done) return "";
                    return this.judgeStatus.data[x].icon;

                }, get_color: function (x) {
                    if (!this.judgeStatus.done) return "black";
                    return this.judgeStatus.data[x].color;
                }, get_text(x) {
                    if (!this.judgeStatus.done) return x;
                    if (this.judgeStatus.data.hasOwnProperty(x))
                        return this.judgeStatus.data[x].text;
                    else return x;
                }
            }
        });
        $.post("/api/get_judge_status").done(ctx => {
            ctx = JSON.parse(ctx);
            judge_status.done = true;
            Vue.set(judge_status, "data", ctx.data);
            // judge_status.data = ctx.data;
        });
        var sidebar;
        let baseObject;
        const converter = new showdown.Converter({
            extensions: [
                {
                    type: 'output', regex: /\$\$([\S\s]+?)\$\$/g, replace: (x, y) => {
                        // console.log(x);
                        // console.log(y);

                        let result = katex.renderToString(y, {
                            throwOnError: false,
                            displayMode: true
                        });
                        // console.log(result);
                        // console.log("qwq");
                        return result;
                    }
                },
                {
                    type: 'output', regex: /\$([\S\s]+?)\$/g, replace: (x, y) => {
                        // console.log(x);
                        // console.log(y);
                        let result = katex.renderToString(y, {
                            throwOnError: false,
                            displayMode: false
                        });
                        // console.log(result);
                        // console.log("qwq");
                        return result;
                    }
                }
            ], tables: true, literalMidWordUnderscores: true
        });
        $(document).ready(() => {
            // $("a").forEach((x) => {
            //     if (!x.attr("no-new-tab")) x.attr("target", "_blank");
            // });
            baseMixin = {
                data: {
                    base: {
                        isLogin: false, username: "", uid: -1, email: ""
                    }
                }, methods: {
                    makeHTML(v) {
                        return converter.makeHtml(v);
                    }, md5: hex_md5,
                    md5WithSalt(v) {
                        return md5WithSalt(v);
                    }
                }
            };
            sidebar = new Vue({
                delimiters: ['{[', ']}'],
                el: "#main-sidebar",
                mixins: [baseMixin],
                data: {
                    show_discussion_detail: false
                }, methods: {
                    logout: function () {
                        $.post("/api/logout").done((ctx) => {
                            ctx = JSON.parse(ctx);
                            window.location.reload()
                        })
                    }, md5: hex_md5
                }, mounted() {
                    this.$nextTick(() => {
                        // $(".dropdown").dropdown();
                        // $("#discussion-item").popup();
                        // $("#user-button").popup({
                        //     popup: $("#user-popup-content"),
                        //     position: "right center",
                        //     inline: true
                        // });

                    });
                }
            })
            $.post("/api/query_login_state").done((ctx) => {
                ctx = JSON.parse(ctx);
                baseMixin.data.base.isLogin = ctx.result;
                if (ctx.result) {
                    baseMixin.data.base.username = ctx.username;
                    baseMixin.data.base.email = ctx.email;
                    baseMixin.data.base.uid = ctx.uid;
                    baseMixin.data.base.mangable = ctx.backend_managable;

                }
            });

        });

    </script>
    {%block head%}{%endblock%}
</head>

<body style="background-color: rgb(236, 233, 233)">
    <div class="ui sidebar vertical labeled icon menu" id="main-sidebar">
        <a class="item" href="/">
            <i class="home icon"></i>
            主页
        </a>
        <a class="item" href="/problems/1">
            <i class="tasks icon"></i>
            题库
        </a>
        <a class="item" href="/submissions/1">
            <i class="hdd icon"></i>
            提交
        </a>
        <a class="item" href="/team">
            <i class="address book icon"></i>
            团队
        </a>
        <a class="item" href="/problemset/list/1">
            <i class="book icon"></i>
            习题集
        </a>
        <a class="item" href="/contests/1">
            <i class="chart line icon"></i>
            比赛
        </a>
        <div class="item" v-on:click="show_discussion_detail=!show_discussion_detail" style="cursor: pointer;">
            <i class="keyboard outline icon"></i>
            讨论
        </div>
        <a class="item" target="_blank" href="/discussions/discussion.global/1" v-if="show_discussion_detail">全局讨论</a>
        <a class="item" target="_blank" href="/discussions/discussion.problem.global/1"
            v-if="show_discussion_detail">题目全局讨论</a>
        <!-- <a class="item" target="_blank" href="/discussions/discussion.problem/1"
            v-if="show_discussion_detail">全部题目讨论</a> -->
        <a class="item" target="_blank" href="/ranklist/1"><i class="signal icon"></i>排名</a>
        <a class="item" target="_blank" href="/ide" v-if="base.isLogin">
            <i class="code icon"></i>
            在线IDE</a>
        <a class="item" target="_blank" href="/help">
            <i class="help circle icon"></i>
            帮助</a>
        <a class="item" target="_blank" href="/login" v-if="!base.isLogin">
            请登录...
        </a>
        <a class="item" href="/register" v-if="!base.isLogin">
            或者注册...
        </a>
        <a class="item" :href="'/profile_edit/'+base.uid" v-if="base.backend_managable" target="_blank">
            <i class="address card icon"></i>
            个人信息编辑
        </a>
        <a class="item" href="/admin" v-if="base.mangable" target="_blank">
            <i class="sitemap icon"></i>
            后台管理
        </a>
        <a class="item" :href="'/profile/'+base.uid" v-if="base.isLogin">
            <img class="ui avatar image" :src="'https://www.gravatar.com/avatar/'+md5(base.email)"></img>
            <span>{[base.username]}</span>
        </a>


        <a class="item" v-on:click="logout" v-if="base.isLogin"><i class="x icon"></i>登出</a>
    </div>
    <div class="pusher" style="background-color: rgb(236, 233, 233);">
        <div class="ui" style="margin-top:50px;margin-left:50px;top:50px;position: fixed">
            <button class="circular ui huge green floating icon button"
                onclick="$('#main-sidebar') .sidebar('setting', 'transition', 'overlay').sidebar('toggle')"><i
                    class="icon plus"></i></button>
        </div>
        <div class="ui main container" style="margin-top:70px;margin-bottom:70px">
            {%block body%}{%endblock%}
        </div>
        <div class="ui center aligned  container">
            <div style="color: darkgrey">
                {{APP_NAME}} Powered by <a href="https://gitee.com/yutong_java/HelloJudge2">HelloJudgeV2</a>
            </div>
        </div>
    </div>
    <div class="ui tiny modal" id="global-error-model">
        <div class="ui header">
            发生错误
        </div>
        <div class="content">
            <div class="ui error message">
                <div class="ui header">
                    <h3 id="global-error-header"></h3>
                </div>
                <p id="global-error-text"></p>
            </div>
        </div>
        <div class="actions">
            <a class="ui blue approve button" href="/">返回主页</a>
            <div class="ui green approve button">关闭</div>
        </div>
    </div>
</body>

</html>